<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>websocket实现消息推送</title>
    <script>
        window.addEventListener("load",function (event) {
            let output = document.getElementById("output")
            let input = document.getElementById("input")
            let ws
            let print = function (message) {
                let d=document.createElement("div")
                d.innerHTML = message
                output.appendChild(d)
            }

            document.getElementById("open").onclick = function (event) {
                if(ws){
                    return false
                }
                ws = new WebSocket("ws://localhost:8888/ws")
                ws.onopen = function (event) {
                    print("打开")
                }
                ws.onclose = function (event) {
                    print("关闭")
                    ws = null
                }

                ws.onmessage = function (event) {
                    print("响应："+event.data)
                }
                ws.onerror = function (event) {
                    print("错误："+event.data)
                }
                return false
            }

            document.getElementById("send").onclick = function (event) {
                if(!ws){
                    return false
                }
                print("发送："+input.value)
                ws.send(input.value)
                return false
            }

            document.getElementById("close").onclick = function (event) {
                ws.close()
                return false
            }
        })
    </script>
</head>
<body>
    <table>
        <tr>
            <td valign="top" width="50%">
                <p>
                    点击:<br>
                    “打开”和服务端创建一个连接。<br>
                    "发送"发送一个消息给服务端。<br>
                    "关闭"去关闭连接.<br>
                    你可以改变消息Message并且发送多次.<br>
                </p>
                <form>
                    <button id="open">打开</button>
                    <button id="close">关闭</button><br>
                    <input  id="input" type="text" value="Websocket —— Go">
                    <button id="send">发送</button><br>
                </form>
            </td>
            <td valign="top" width="50%">
                <div id="output"></div>
            </td>
        </tr>
    </table>

</body>
</html>